package com.qriver.ratelimiter.annotation;


import com.google.common.collect.Lists;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 建立切面，拦截并处理限流注解
 */
@Aspect
@Component
public class AccessLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Long> rateLimitLua;

    @Pointcut("@annotation(AccessLimiter)")
    public void cut() {

    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {
        // 1. 获得方法签名，作为method Key
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        AccessLimiter annotation = method.getAnnotation(AccessLimiter.class);
        if (annotation == null) {
            return;
        }
        //获取注解的属性值
        String key = annotation.methodKey();
        Integer limit = annotation.limit();
        Integer timeout = annotation.timeout();

        // 如果没设置methodkey, 从调用方法签名生成自动一个key
        if (StringUtils.isEmpty(key)) {
            Class[] type = method.getParameterTypes();
            key = method.getClass() + method.getName();
            if (type != null) {
                String paramTypes = Arrays.stream(type)
                        .map(Class::getName)
                        .collect(Collectors.joining(","));
                key += "#" + paramTypes;
            }
        }

        // 2. 调用Redis
        Long flag = stringRedisTemplate.execute(
                rateLimitLua, // Lua 脚本
                Lists.newArrayList(key), // Lua脚本中的Key列表，即限流的key
                limit.toString(), // Lua脚本Value列表，即限流的阈值
                timeout.toString() //超期时间
        );

        if (flag == -1) {
            throw new RuntimeException("Your access is blocked");
        }
    }

}
